//
//  ZyaTenderHelper.swift
//  ANOA
//
//  Created by 邱仙凯 on 2020/3/28.
//  Copyright © 2020 zwb. All rights reserved.
//

import UIKit
let TradeDic: [String : String] = ["1":"猪业","2":"饲料","3":"原料","4":"物流","5":"药品"]
let BuyDic: [String : String] = ["0":"卖方","1":"买方"]
let YBDic: [String : String] = ["0":"未邀标","1":"已邀标"]
let AutoDic: [String : String] = ["0":"不自动","1":"自动"]
class ZyaTenderHelper: NSObject,tenderFilterable {
    
    
    
     let titles_jp = ["状态","区域","时间","更多"]
    let titles_zb = ["状态","区域","时间","更多"]
  
    let source1_zb = ["时间排序","价格排序"]
    let source1_jp = ["时间排序","价格排序"]
 
    let source_tb_status = [
        "全部",
        "3日内",
        "7日内",
        "1月内",
        "3月内"
    ]
    let source_jp_status = [
        "全部",
        "3日内",
        "7日内",
        "1月内",
        "3月内"
    ]
    
    
    var dropMenu:GHDropMenu?
    
    var inviteClosure:(()->())?
    var callTableRefreshClosure:(()->())?
    
    
    func go2TenderAddController(controller:UIViewController,idkey:String,excuteType:OperateType,refreshClosure:@escaping (()->())) {
        
    }
    
    func go2TenderTbController(listType:TBandJPType,controller:UIViewController,z_tb_id:String = "",z_zb_id:String = "",z_bid_id:String = "",excuteType:OperateType,tbInfoH:CGFloat? = nil,model:ZtbContentModel? = nil,refreshClosure:@escaping (()->())) {
        
    }
    
    func go2CarInfo(idkey:String,controller:UIViewController) {
       
    }
    
    func go2DepositController(controller:UIViewController) {
        
        
    }
    
    func go2TenderTbDetailController(listType:TBandJPType,controller:UIViewController,idkey:String,innerType:ZTBInnerType) {
        
    }
    func getHeaderHeight(webheight:Double,imgHeight:Double) -> CGFloat {
        return CGFloat(webheight + 1000 + imgHeight)
    }
    
    func getZBInfoAPI(listType:TBandJPType = .TB,id_key:String) -> API {
        if listType == .TB {
            return API.queryZbInfo(id_key: id_key)
        } else {
            return API.queryJpInfo(jp_id: id_key)
        }
        
    }
    

    
    func go2AgreementController(listType:TBandJPType,controller:UIViewController,z_zb_id:String) {
        
        
        
    }
    func go2FeedbackForm(zZbId:String = "",zZbNo:String = "",zTitle:String = "",controller:UIViewController) {

    }
    func downloadFiles(zbFiles:[ZbFile]) {
        
    }
    func setRecordMark(z_record_id:String,z_mark:String,z_type:String) {
        
    }
    
    func unReferTb(controller:TenderListController,idkey:String) {
        
    }
    func publishTender(controller:UIViewController) {
        
    }
    
    func titleStrToAPI(listType:TBandJPType,titleStr:ZTBInnerType,startDate:String,endDate:String,maxValue:String,minValue:String,zprovince:String,zcity:String,searchTitle:String,page:Int,z_zb_id:String,sortType:String,z_status:String,outDate:String = "",category:String = "",followTag:String = "0") -> API {
        
        var api:API?
        switch titleStr {
    
        case .zbInfo_followTagOA:
            api = API.tender(.queryZbInfoList(z_begin_dt: startDate, z_end_dt: endDate, z_city: zcity, z_price_min: minValue, z_price_max: maxValue, page: "\(page)", size: "10", z_title: searchTitle, z_sort: sortType, query_type: "",z_status: z_status,followTag: followTag,s_data_source: ""))
        case .jpInfo_followTagOA:
            api = API.queryJpInfoList(z_begin_dt: startDate, z_end_dt: endDate,z_out_dt: outDate, z_city: zcity, z_price_min: minValue, z_price_max: maxValue, page: "\(page)", size: "10", z_title: searchTitle, z_sort: sortType, query_type: "4",z_status: z_status,followTag: "1",z_contract_state: "")
        case .jpInfo_oaOA:
            api = API.queryJpInfoList(z_begin_dt: startDate, z_end_dt: endDate,z_out_dt: outDate, z_city: zcity, z_price_min: minValue, z_price_max: maxValue, page: "\(page)", size: "10", z_title: searchTitle, z_sort: sortType, query_type: "4",z_status: z_status,followTag: "",z_contract_state: "")
        case .tbRecordKHW:
            api = API.tender(.queryTbInfoList(page: "\(page)", size: "10", z_zb_id: z_zb_id, z_title: searchTitle,followTag: followTag))
        case .tbRecord_followTagOA:
            api = API.tender(.queryTbInfoList(page: "\(page)", size: "20", z_zb_id: z_zb_id, z_title: searchTitle,followTag: followTag))
        case .chujiaRecordKHW,.chujiaRecordJP:
            api = API.queryBidInfoList(page: "\(page)", size: "10", jp_id: z_zb_id, z_title: searchTitle, z_sort: "1",s_data_source: "0")
        default:
            print("22")
        }
        
        return api!
        
        
    }
    
    
    
    func configSubView(superV:UIViewController,tableV:UITableView,bottomV:UIView) {
        
        tableV.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height: superV.view.frame.height)
        superV.view.addSubview(tableV)
        
    }
    
    func setBtnTitle(listType:ZTBInnerType,zAuditMark:String,btn2:UIButton) -> String {
        
        if listType == .zbInfo_ylOA || listType == .zbInfo_wlOA || listType == .zbInfo_drugOA {
            
            if zAuditMark == "0" || zAuditMark == "2" {
                
                btn2.setTitle("", for: .normal)
            } else if zAuditMark == "1" {
                
                btn2.setTitle("投标记录", for: .normal)
                
            } else if zAuditMark == "9" {
                btn2.setTitle("", for: .normal)
            }
        } else if listType == .zbInfo_followTagOA {
            btn2.setTitle("投标情况", for: .normal)
        }
        return btn2.titleLabel!.text.unwrap
        
    }
    func go2TenderRecord(controller:UIViewController,id:String) {
        let  vc = TenderRecordVC(titleStr: .tbRecordKHW, z_zb_id: id)
        controller.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    func isFangke() -> Bool {
        return false
    }
    
    func configRightItem4Tender(listType:TBandJPType,action:(()->())?) -> UIBarButtonItem? {
        self.inviteClosure = action
        
        let item = UIBarButtonItem(title: listType == .TB ? "邀标情况" : "邀拍情况", style: .done, target: self, action: #selector(rightItemAction))
        return item
    }
    
    @objc func rightItemAction() {
        if let clo = self.inviteClosure {
            clo()
        }
        
    }
    
    func getInviteListAction(listType:TBandJPType,fromVC:UIViewController,z_zb_id:String) {
        if listType == .TB {
            KSNetwork.shared.doRequest(API.queryInvitationList(z_zb_id: z_zb_id, page: "1", size: "30")) { (data:BaseResult<InviteModel>) in
                if data.flag == TRUE {
                    
                    var allArr = [nameAndModel<InviteModel>]()
                    for item in data.infos! {
                        let one_x = nameAndModel(shows: ["法人:\(item.legalMan.unwrap)","手机号:\(item.providerTel.unwrap)",item.providerNm.unwrap,"","税号:\(item.taxNo.unwrap)"], model: item)
                        allArr.append(one_x)
                    }
                    
                    let cle:(nameAndModel<InviteModel>)->() = { one in
                        
                    }
                    
                    let vc = KSSingleSelectUtil.initForPush(title: "邀标列表", allArr: allArr,backClosure: cle,selectType: .onlyShow)
                    fromVC.navigationController?.pushViewController(vc, animated: true)
                    
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            KSNetwork.shared.doRequest(API.queryJpInvitationList(jp_id: z_zb_id, page: "1", size: "30")) { (data:BaseResult<InviteModel>) in
                if data.flag == TRUE {
                    
                    var allArr = [nameAndModel<InviteModel>]()
                    for item in data.infos! {
                        let one_x = nameAndModel(shows: [item.org_name.unwrap,"",item.client_name.unwrap,"",item.client_desc.unwrap], model: item)
                        allArr.append(one_x)
                    }
                    
                    let cle:(nameAndModel<InviteModel>)->() = { one in
                        
                    }
                    
                    let vc = KSSingleSelectUtil.initForPush(title: "邀拍列表", allArr: allArr,backClosure: cle,selectType: .onlyShow)
                    fromVC.navigationController?.pushViewController(vc, animated: true)
                    
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }
        
    }
    func configSortType(index:String) {
        self.filterPa!.zSort = index
    }
    
    func configParam(s2:Int) {
        
        // 1、将「时间」改成「状态」，可以查询全部、未开始、进行中、已结束、已流标、已中标状态的单据
        // 招标状态?0:未开始;  1:已中标;2:进行中;3:已结束;4:已流标
        
        if s2 == 0 {
            self.filterPa!.zStatus = "0,1,2,3,4"
            
        } else if s2 == 1 {
            self.filterPa!.zStatus = "0"
            
        } else if s2 == 2 {
            self.filterPa!.zStatus = "2"
            
        } else if s2 == 3 {
            self.filterPa!.zStatus = "3"
        } else if s2 == 4 {
            self.filterPa!.zStatus = "1"
        } else if s2 == 5 {
            self.filterPa!.zStatus = "4"
        }
        
    }
    
    
}


extension ZyaTenderHelper {
    
    func listFilterAction(listType:TBandJPType) {
        if dropMenu.isNone {
            dropMenu = getDropMenu(listType: listType)
        }
        
        dropMenu!.show()
    }
    
    func delegateSearchAction() {
        if let clo = self.callTableRefreshClosure {
            clo()
        }
        
    }
    
}

protocol getDepositRemainable: AnyObject {
    func getDepositValue(valueClo:((Bool,String)->())?)
}
extension getDepositRemainable {
    
    func getDepositValue(valueClo:((Bool,String)->())?) {
        
    }
    
}
let paixuArr = ["默认排序","综合排序"]

// 招投标过滤协议
protocol tenderFilterable where Self: GHDropMenuDelegate {
    
    
    func getDropMenu (listType:TBandJPType) -> GHDropMenu
    var filterPa:tenderfilterParam? { get set }
    
    func delegateSearchAction()
    
}

var timeRangeArr = [
    "全部",
    "3日内",
    "7日内",
    "1月内",
    "3月内"
]

extension tenderFilterable {
    
    var filterPa: tenderfilterParam? {
        set {
            objc_setAssociatedObject(self, &RuntimeKeys.tenderfilterPaKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            var fp = (objc_getAssociatedObject(self, &RuntimeKeys.tenderfilterPaKey) as? tenderfilterParam)
            if fp.isNone {
                fp = tenderfilterParam()
                fp!.zSort = "1"
                fp!.zStatus = "0,1,2,3,4"
            }
            return fp
        }
    }
    
    func getDropMenu(listType:TBandJPType) -> GHDropMenu {
        
        let  configuration = GHDropMenuModel()
        configuration.titles = creaFilterData4Goods(listType:listType)
        configuration.recordSeleted = true
        
        let dropMenu = GHDropMenu.creatDropFilterMenuWidthConfiguration(configuration) { (tagArray) in
            self.getStrWith4Tender(tagArray: tagArray as! [GHDropMenuModel])
        }
        dropMenu.delegate = self
        dropMenu.durationTime = 0.3
        return dropMenu
    }
    
    
    func creaFilterData4Goods(listType:TBandJPType) -> [GHDropMenuModel] {
        
        
        // 金额
       var dataArray_price = [GHDropMenuModel]()
       let one_n = GHDropMenuModel()
       one_n.placeholderLeft = "请输入最小金额"
       one_n.placeholderRight = "请输入最大金额"
       dataArray_price.append(one_n)
       
       // 类型
       var dataArray_leixing = [GHDropMenuModel]()
       for item in leixingArr {
           let one = GHDropMenuModel()
           one.tagName = item
           dataArray_leixing.append(one)
       }
       
       // 排序
       var dataArray_paixu = [GHDropMenuModel]()
       for item in paixuArr {
           let one = GHDropMenuModel()
           one.tagName = item
           dataArray_paixu.append(one)
       }
       
       
       // 时间
       var dataArray_time = [GHDropMenuModel]()
       let one = GHDropMenuModel()
       one.beginPlaceholder = "选择出栏日期"
       one.hiddenRight = true
       dataArray_time.append(one)
       
       var sectionHeaderTitles:[String]!
       if listType == .TB {
           sectionHeaderTitles = ["排序","类型","金额","出栏时间"]
       } else {
           sectionHeaderTitles = ["排序","金额","出栏时间"]
       }
       
       
       var sections = [GHDropMenuModel]()
       
       for title in sectionHeaderTitles {
           let one = GHDropMenuModel()
           one.sectionHeaderTitle = title
           if title == "金额" {
               one.dataArray = dataArray_price
               one.filterCellType = .input
           }
           if title == "出栏时间" {
               one.dataArray = dataArray_time
               one.filterCellType = .timeChose
           }
           if title == "排序" {
               one.dataArray = dataArray_paixu
               one.filterCellType = .tag
           }
           if title == "类型" {
               one.dataArray = dataArray_leixing
               one.filterCellType = .tag
           }
           
           sections.append(one)
       }
       
       var titlesArray = [GHDropMenuModel]()
       
       let finalOne = GHDropMenuModel()
       finalOne.sectionCount = 3.01
       finalOne.menuWidth = KSGlobal.screenW * 0.9
       finalOne.sections = sections
       titlesArray.append(finalOne)
       
       return titlesArray
       
   }
    func getContentStr(listType:TBandJPType,info:ZtbContentModel) -> String {
        
        if listType == .TB {
            return info.zbInfo.unwrap.replacingOccurrences(of: "#", with: "\n")
        } else {
            return info.jpInfo.unwrap.replacingOccurrences(of: "#", with: "\n")
        }
        
        
        
    }
    // 选择后的回调
    func getStrWith4Tender(tagArray:[GHDropMenuModel]) {
        
        
        for i in 0..<tagArray.count {
            switch i {
                
            case 0:
                filterPa!.minMoney = tagArray[i].minValue
                filterPa!.maxMoney = tagArray[i].maxValue
            case 1:
                
                if tagArray[i].tagSeleted {
                    
                    
                    if tagArray[i].tagName == "全部" {
                        filterPa!.startDate = ""
                        filterPa!.endDate = ""
                        
                    } else if tagArray[i].tagName == "3日内" {
                        filterPa!.startDate = Date.todayPres(3)
                        filterPa!.endDate = Date.today
                        
                    } else if tagArray[i].tagName == "7日内" {
                        filterPa!.startDate = Date.todayPres(7)
                        filterPa!.endDate = Date.today
                        
                    } else if tagArray[i].tagName == "1月内" {
                        filterPa!.startDate = Date.preMonthsWithNowday(1)
                        filterPa!.endDate = Date.today
                        
                    } else if tagArray[i].tagName == "3月内" {
                        filterPa!.startDate = Date.preMonthsWithNowday(3)
                        filterPa!.endDate = Date.today
                    }
                    
                } else {
                    filterPa!.startDate = ""
                    filterPa!.endDate = ""
                }
            case 2:
                filterPa!.outDate = tagArray[i].beginTime
                
            default:
                break
            }
            
        }
        
        self.delegateSearchAction()
        
    }
    
}
func go2TenderInfoController(listType:TBandJPType,fromVC:UIViewController,idkey:String,voccd:String = "",processid:String = "",enterType:EnterType = .none,todoType:TodoType = .normal,taskId:String = "",innerType:ZTBInnerType) {
    
    let vc = OATenderInfoVC(listType: listType)
    vc.idkey = idkey
    vc.voccd = voccd
    vc.processid = processid
    vc.innerType = innerType
    vc.enterType = enterType
    vc.todoType = todoType
    vc.taskidFromTodoList = taskId
    fromVC.navigationController?.pushViewController(vc, animated: true)
}
